package cn.ytxy.ivos.dict.service.impl;


import cn.ytxy.ivos.base.response.PageData;
import cn.ytxy.ivos.base.utils.CacheUtils;
import cn.ytxy.ivos.dict.mapper.DictMapper;
import cn.ytxy.ivos.dict.pojo.dto.DictQuery;
import cn.ytxy.ivos.dict.pojo.entity.Dict;
import cn.ytxy.ivos.dict.pojo.vo.DictVO;
import cn.ytxy.ivos.dict.service.DictService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * @ClassName DictServiceImpl
 * @Description TODO
 * @Author renhong~Deng
 * @Date 2025/5/11 16:28
 * @Version 1.0
 */

@Slf4j
@Service
public class DictServiceImpl implements DictService {

    @Autowired
    private DictMapper dictMapper;

    @Autowired
    CacheUtils cacheUtils;

    @Override
//    public List<DictVO> selectDict(DictQuery dictQuery) {
    public PageData selectDict(DictQuery dictQuery) {
        List<DictVO> list = dictMapper.select(dictQuery);

        //准备PageData对象用来装返回给前端的数据
        PageData dictData = new PageData();
        //向PageData对象中装存入当前页字典数据
        dictData.setList(list);
        //向PageData对象中装存入总记录数
        dictData.setTotal(dictMapper.selectDictCount(dictQuery));
        //返回封装好的对象
        return dictData;
    }

    @Override
    public void saveDict(DictQuery dictQuery) {
        Dict dict = new Dict();
        BeanUtils.copyProperties(dictQuery, dict);
        if (dictQuery.getId() == null) {
            dict.setCreateTime(new Date());
            dictMapper.insert(dict);
        } else {
            dict.setUpdateTime(new Date());
            dictMapper.update(dict);
        }
    }

    @Override
    public void deleteDict(Long id) {
        log.debug("Service层删除字典信息，id={}", id);
        //同时清空redis中与该字典相关的缓存数据
        DictQuery dictQuery = new DictQuery();
        dictQuery.setId(id);
        List<DictVO> list = dictMapper.selectDict(dictQuery);
        if (list != null && !list.isEmpty()) {
            DictVO dictVO = list.get(0);
            //根据dict的code删除之前的redis缓存
            cacheUtils.delete("dictOption" + dictVO.getCode());
        }
        dictMapper.deleteById(id);
    }


}
